﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace uam_fps_game.Views
{
    public class ViewManager
    {
        public ViewManager(GraphicsDevice device, IServiceProvider serviceProvider)
        {
            mDevice = device;
            mServiceProvider = serviceProvider;

            mViewTransitions = new List<ViewTransition>();
            mViews = new List<View>();
        }

        private GraphicsDevice mDevice;
        private IServiceProvider mServiceProvider;

        private List<ViewTransition> mViewTransitions;
        private List<View> mViews;
        private View mActiveView;

        public void AddTransition(ViewTransition trans)
        {
            mViewTransitions.Add(trans);
        }

        public void AddView(View view)
        {
            if (!mViews.Contains(view))
            {
                mViews.Add(view);
            }
        }

        public void RemoveView(View view, bool unload)
        {
            if (unload)
            {
                view.Unload();
            }

            mViews.Remove(view);
        }

        /// <summary>
        /// View must be added previously with AddView().
        /// </summary>
        /// <param name="view"></param>
        /// <returns>Prevois view</returns>
        public View SetActiveView(View view)
        {
            if (mViews.Contains(view))
            {
                View old = mActiveView;
                if (!view.Loaded)
                {
                    view.Load(mDevice, mServiceProvider);
                }
                mActiveView = view;
                return old;
            }
            return null;
        }

        private void ProcessResult(ViewState result)
        {
            foreach (ViewTransition trans in mViewTransitions)
            {
                if (trans.ViewFrom == mActiveView && trans.ViewState == result)
                {
                    if (mViews.Contains(trans.ViewTo))
                    {
                        SetActiveView(trans.ViewTo);
                    }
                }
            }
        }

        public void Update(float deltaTime)
        {
            if (mActiveView != null)
            {
                ViewState result = mActiveView.GetState();
                if (result != null)
                {
                    ProcessResult(result);
                }
            }

            if (mActiveView != null)
            {
                mActiveView.Update(deltaTime);
            }
        }

        public void Draw()
        {
            if (mActiveView != null)
            {
                mActiveView.Draw();
            }
        }
    }
}
